package com.kila.dao.impl;

import com.kila.dao.Account;
import com.kila.dao.AccountDao;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class AccountDaoImpl implements AccountDao {
    private JdbcTemplate jdbcTemplate ;

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public AccountDaoImpl() {
        super();
    }

    @Override
    public int addAccount(Account account) {
           String sql ="insert into account(username,balance) value(?,?) ";
           Object[] obj = new Object[]{
                   account.getUsername(),
                   account.getBalance()
           };
           int num = this.jdbcTemplate.update(sql,obj);
           return num;
    }

    @Override
    public int updateAccount(Account account) {
           String sql = "UPDATE account SET username=?,balance=? WHERE id=? ";
            Object[] obj = new Object[]{

                    account.getUsername(),
                    account.getBalance(),
                    account.getId()
            };
           int num = this.jdbcTemplate.update(sql,obj);
           return num;
    }

    @Override
    public int deleteAccount(Integer id) {
       String sql = "DELETE FROM account WHERE id = ?";

       int num = this.jdbcTemplate.update(sql, id);
        return num;
    }

    @Override
    public Account queryById(Integer id) {
       String sql = "SELECT * FROM account WHERE id = ?";
       //创建1个新的BeanPropertyRowMapper
        RowMapper<Account> rowMapper =
                new BeanPropertyRowMapper<Account>(Account.class);
        //将id绑定到SQL语句中，并通过RowMapper返回一个Object类型的单行记录
        return this.jdbcTemplate.queryForObject(sql,rowMapper,id);

    }

    @Override
    public List<Account> queryAllAccount() {
        String sql ="SELECT * FROM account";
        //创建一个新的BeanPropertyRowMapper对象
        RowMapper<Account> rowMapper=
                new BeanPropertyRowMapper<Account>(Account.class);
        return this.jdbcTemplate.query(sql,rowMapper);
    }
}
